<template>
  <div class="appointment-page">
    <header class="header">
      <div class="back-button" @click="goBack">
        <span>&lt;</span>
      </div>
      <h1>预约服务</h1>
      <div class="right-icons">
        <span class="icon">⋯</span>
      </div>
    </header>

    <div class="service-info">
      <h2>{{ params.serviceName || '护士到家服务' }}</h2>
      <!-- <div class="price">¥{{ params.price || 99 }}</div> -->
    </div>

    <div class="form-section">
      <h3>预约信息</h3>
      <div class="form-item">
        <label>服务对象</label>
        <div class="input-wrapper">
          <input type="text" v-model="form.patientName" placeholder="请输入服务对象姓名" />
        </div>
      </div>
      <div class="form-item">
        <label>联系电话</label>
        <div class="input-wrapper">
          <input type="tel" v-model="form.phone" placeholder="请输入联系电话" />
        </div>
      </div>
      <div class="form-item">
        <label>服务日期</label>
        <div class="input-wrapper date-picker" @click="showDatePicker = true">
          <span>{{ form.date || '请选择服务日期' }}</span>
          <span class="arrow">▼</span>
        </div>
      </div>
      <div class="form-item">
        <label>服务时间</label>
        <div class="input-wrapper time-picker" @click="showTimePicker = true">
          <span>{{ form.time || '请选择服务时间' }}</span>
          <span class="arrow">▼</span>
        </div>
      </div>
      <div class="form-item">
        <label>服务地址</label>
        <div class="input-wrapper">
          <input type="text" v-model="form.address" placeholder="请输入详细地址" />
        </div>
      </div>
      <div class="form-item">
        <label>备注信息</label>
        <div class="input-wrapper">
          <textarea v-model="form.notes" placeholder="请输入备注信息（选填）"></textarea>
        </div>
      </div>
    </div>

    <div class="agreement">
      <input type="checkbox" id="agree" v-model="form.agreed" />
      <label for="agree">我已阅读并同意<span class="link">《服务协议》</span>和<span class="link">《隐私政策》</span></label>
    </div>

    <!-- <div class="summary">
      <div class="summary-item">
        <span>服务费用</span>
        <span class="price">¥{{ params.price || 99 }}</span>
      </div>
      <div class="summary-item" v-if="form.coupon">
        <span>优惠券</span>
        <span class="discount">-¥{{ form.coupon }}</span>
      </div>
      <div class="summary-item total">
        <span>实付款</span>
        <span class="price">¥{{ calculateTotal() }}</span>
      </div>
    </div> -->

    <!-- 底部占位，防止内容被底部固定栏遮挡 -->
    <div class="bottom-placeholder"></div>

    <div class="submit-bar">
      <!-- <div class="total-price">
        <span>合计：</span>
        <span class="price">¥{{ calculateTotal() }}</span>
      </div> -->
      <button class="submit-button" :disabled="!form.agreed"  @click="submitOrder">提交订单</button>
    </div>

    <!-- 日期选择器弹窗 -->
    <div class="modal" v-if="showDatePicker">
      <div class="modal-content">
        <div class="modal-header">
          <h3>选择日期</h3>
          <span class="close" @click="showDatePicker = false">×</span>
        </div>
        <div class="date-grid">
          <div 
            v-for="date in availableDates" 
            :key="date.value"
            class="date-item"
            :class="{ active: form.date === date.label }"
            @click="selectDate(date.label)"
          >
            {{ date.label }}
          </div>
        </div>
      </div>
    </div>

    <!-- 时间选择器弹窗 -->
    <div class="modal" v-if="showTimePicker">
      <div class="modal-content">
        <div class="modal-header">
          <h3>选择时间</h3>
          <span class="close" @click="showTimePicker = false">×</span>
        </div>
        <div class="time-grid">
          <div 
            v-for="time in availableTimes" 
            :key="time"
            class="time-item"
            :class="{ active: form.time === time, disabled: isTimeDisabled(time) }"
            @click="!isTimeDisabled(time) && selectTime(time)"
          >
            {{ time }}
          </div>
        </div>
      </div>
    </div>

    <!-- 订单提交成功弹窗 -->
    <div class="modal" v-if="showSuccessModal">
      <div class="modal-content success-modal">
        <div class="success-icon">✓</div>
        <h3>预约成功</h3>
        <p>您的订单已提交成功，我们会尽快安排专业护士与您联系</p>
        <p>订单号：{{ orderNumber }}</p>
        <button class="primary-button" @click="goBack">返回首页</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits } from 'vue';

const props = defineProps({
  params: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['go-back']);

const form = ref({
  patientName: '',
  phone: '',
  date: '',
  time: '',
  address: '',
  notes: '',
  coupon: 0,
  agreed: false
});

const showDatePicker = ref(false);
const showTimePicker = ref(false);
const showSuccessModal = ref(false);
const orderNumber = ref('');

// 生成未来7天的日期
const availableDates = computed(() => {
  const dates = [];
  const today = new Date();
  
  for (let i = 0; i < 7; i++) {
    const date = new Date(today);
    date.setDate(today.getDate() + i);
    
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    
    const dayNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    const dayName = dayNames[date.getDay()];
    
    dates.push({
      value: `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`,
      label: `${month}月${day}日 ${dayName}`
    });
  }
  
  return dates;
});

// 可选时间段
const availableTimes = [
  '08:00-09:00', '09:00-10:00', '10:00-11:00', '11:00-12:00',
  '13:00-14:00', '14:00-15:00', '15:00-16:00', '16:00-17:00',
  '17:00-18:00', '18:00-19:00', '19:00-20:00'
];

// 模拟一些时间段已被预约
const isTimeDisabled = (time) => {
  const disabledTimes = ['09:00-10:00', '14:00-15:00', '18:00-19:00'];
  return disabledTimes.includes(time);
};

const selectDate = (date) => {
  form.value.date = date;
  showDatePicker.value = false;
};

const selectTime = (time) => {
  form.value.time = time;
  showTimePicker.value = false;
};

const calculateTotal = () => {
  return (props.params.price || 99) - (form.value.coupon || 0);
};

// 生成随机订单号
const generateOrderNumber = () => {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
  return `${year}${month}${day}${random}`;
};

const submitOrder = () => {
  if (!validateForm()) {
    return;
  }
  
  // 生成订单号
  orderNumber.value = generateOrderNumber();
  
  // 创建订单对象
  const order = {
    id: orderNumber.value,
    serviceName: props.params.serviceName || '护士到家服务',
    price: calculateTotal(),
    status: '待服务',
    createdAt: new Date().toISOString(),
    serviceDate: form.value.date,
    serviceTime: form.value.time,
    patientName: form.value.patientName,
    phone: form.value.phone,
    address: form.value.address,
    notes: form.value.notes,
    source: props.params.source || 'home'
  };
  
  // 保存到本地存储
  saveOrderToLocalStorage(order);
  
  // 显示成功弹窗
  showSuccessModal.value = true;
};

const saveOrderToLocalStorage = (order) => {
  // 获取现有订单
  let orders = JSON.parse(localStorage.getItem('nurseOrders') || '[]');
  
  // 添加新订单
  orders.push(order);
  
  // 保存回本地存储
  localStorage.setItem('nurseOrders', JSON.stringify(orders));
};

const validateForm = () => {
  if (!form.value.patientName) {
    alert('请输入服务对象姓名');
    return false;
  }
  
  if (!form.value.phone) {
    alert('请输入联系电话');
    return false;
  }
  
  if (!form.value.date) {
    alert('请选择服务日期');
    return false;
  }
  
  if (!form.value.time) {
    alert('请选择服务时间');
    return false;
  }
  
  if (!form.value.address) {
    alert('请输入服务地址');
    return false;
  }
  
  if (!form.value.agreed) {
    alert('请阅读并同意服务协议和隐私政策');
    return false;
  }
  
  return true;
};

const goBack = () => {
  emit('go-back');
};
</script>

<style scoped>
.appointment-page {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
  max-width: 100vw;
  margin: 0 auto;
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 60px;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 15px;
  background-color: #00a163;
  color: white;
  position: sticky;
  top: 0;
  z-index: 100;
  width: 100%;
}

.back-button {
  font-size: 24px;
  font-weight: bold;
  cursor: pointer;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.header h1 {
  font-size: 18px;
  margin: 0;
  flex: 1;
  text-align: center;
}

.right-icons {
  width: 30px;
  text-align: right;
}

.service-info {
  background-color: white;
  padding: 15px;
  margin-bottom: 10px;
}

.service-info h2 {
  font-size: 18px;
  margin: 0 0 10px 0;
}

.price {
  color: #ff4d4f;
  font-size: 20px;
  font-weight: bold;
}

.form-section {
  background-color: white;
  padding: 15px;
  margin-bottom: 10px;
}

.form-section h3 {
  font-size: 16px;
  margin: 0 0 15px 0;
}

.form-item {
  margin-bottom: 15px;
}

.form-item label {
  display: block;
  font-size: 14px;
  color: #333;
  margin-bottom: 5px;
}

.input-wrapper {
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 10px;
  background-color: white;
}

.input-wrapper input,
.input-wrapper textarea {
  width: 100%;
  border: none;
  outline: none;
  font-size: 14px;
}

.input-wrapper textarea {
  height: 60px;
  resize: none;
}

.date-picker,
.time-picker {
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
}

.arrow {
  color: #999;
  font-size: 12px;
}

.agreement {
  background-color: white;
  padding: 15px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.agreement input {
  margin-right: 5px;
}

.agreement label {
  font-size: 14px;
  color: #666;
}

.link {
  color: #00a163;
}

.summary {
  background-color: white;
  padding: 15px;
  /* margin-bottom: 80px; */
}

.summary-item {
  display: flex;
  justify-content: space-between;
  /* margin-bottom: 10px; */
  font-size: 14px;
}

.summary-item.total {
  font-weight: bold;
  border-top: 1px solid #f0f0f0;
  padding-top: 10px;
  /* margin-top: 10px; */
}

.discount {
  color: #ff4d4f;
}

.submit-bar {
  position: absolute;
  bottom: 100px;
  left: 0;
  right: 0;
  display: flex;
  background-color: white;
  padding: 10px 15px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.total-price {
  flex: 1;
  display: flex;
  align-items: center;
}

.submit-button {
  padding: 10px 25px;
  background-color: #ff4d4f;
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 16px;
  width: 100%;
}

.submit-button:disabled {
  background-color: #ccc;
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 200;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: 90%;
  max-width: 400px;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.modal-header h3 {
  margin: 0;
  font-size: 16px;
}

.close {
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.date-grid,
.time-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  padding: 15px;
}

.date-item,
.time-item {
  padding: 10px;
  text-align: center;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}

.date-item.active,
.time-item.active {
  background-color: #e6f7f1;
  color: #00a163;
  border-color: #00a163;
}

.time-item.disabled {
  background-color: #f5f5f5;
  color: #999;
  cursor: not-allowed;
}

.success-modal {
  padding: 20px;
  text-align: center;
}

.success-icon {
  width: 60px;
  height: 60px;
  background-color: #00a163;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 30px;
  margin: 0 auto 15px;
}

.success-modal h3 {
  font-size: 18px;
  margin: 0 0 10px 0;
}

.success-modal p {
  color: #666;
  margin-bottom: 10px;
}

.primary-button {
  padding: 10px 25px;
  background-color: #00a163;
  color: white;
  border: none;
  border-radius: 20px;
  font-size: 16px;
}

@media screen and (max-width: 375px) {
  .date-grid,
  .time-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

.bottom-placeholder {
  height: 60px;
  width: 100%;
}
</style> 